<?php


namespace app\common\api;


// 微信支付
use app\mass\controller\Oss;

class QyWeChat
{
    protected $app_id;      // 小程序appId
    protected $app_secret;  // 小程序appSecret
    protected $key;         // 商户平台密钥
    protected $mch_id;      // 商户号
    protected $sub_mch_id;  // 子商户号
    protected $sub_app_id;  // 子appId

    private $last_data; // 上次接口请求返回值临时存储


    /**
     * 获取上次接口返回值
     * @return mixed
     * @date 2020/7/20 15:40
     */
    public function get_last_data() {
        return $this->last_data;
    }

    /**
     * 构造方法
     * WeChat constructor.
     * @param string $app_id 小程序appId
     * @param string $app_secret 小程序appSecret
     * @param string $key 商户平台密钥 如果是特约商户, 要用主商户的key
     * @param string $mch_id 商户号
     * @param string $sub_mch_id 子商户号
     * @param string $sub_app_id 子appId
     */
    public function __construct($corpid='', $corpsecret='') {
        $this->corpid      = !empty($corpid) ? $corpid : app()->env->get('qy_wechat_corpid');
        $this->corpsecret  = !empty($app_secret) ? $app_secret :  app()->env->get('qy_wechat_corpsecret');
    }

    
    /**
     * 获取access_token
     * @return string
     * @date 2022/10/11 17:00
     */
    public function get_access_token() {
        $redis  = redis_instance();
        $key    = "QyWeChatAccessToken:{$this->corpid}";
        $refresh_token = true;
        // 判断是否存在access_token
        if($redis->exists($key)) {
            $res = json_decode($redis->get($key), true);
            if(empty($res['expire_time']) || $res['expire_time'] < time()) {
                $refresh_token = true;
            }else {
                $refresh_token = false;
            }
        }
        if($refresh_token) {
            $arr['corpid']     = $this->$corpId;

            $arr['corpsecret'] = $this->$corpsecret;

            $url ="https://qyapi.weixin.qq.com/cgi-bin/gettoken";
            
            $res = json_decode($this->curl('GET', $url, $arr), true);
            
            if ($res['errcode']==0) {
                
                // $access_token = $array['access_token'];

                // $date_time    = date('Y-m-d H:i:s',time());
                $res['expire_time'] = time() + 7000;
                // 存储redis
                $redis->set($key, json_encode($res), 7000);

            } else {

                json_response(0, '获取access_token错误', $res);
            
            }
        }
        return isset($res['access_token']) ? $res['access_token'] : '';
    }
    /**
     * 获取客户详情
     * @return string
     * @date 2022/10/11 17:00
     */
    public function get_contact($ExternalUserID)
    {   
        $access_token = $this->get_access_token();

        $url = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get";

        $arr['access_token'] = $access_token;

        $arr['external_userid'] =  $ExternalUserID;

        $res = json_decode($this->curl('GET', $url, $arr), true);

        if($res['errcode'] == 0 && !empty($res['external_contact']['unionid'])){

           $unionid = $res['external_contact']['unionid'];

           return $unionid;
        }else{

            json_response(0, '获取不到unionid', $res);
        }
    }
    /**
     * xml转数组
     * @param $xml
     * @return mixed
     * @date 2020/6/12 18:26
     */
    private function xml_to_array($xml) {
        //将XML转为array
        $array_data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $array_data;
    }

    /**
     * 数组转xml
     * @param $arr
     * @return string
     * @date 2020/6/12 18:26
     */
    private function array_to_xml($arr) {
        if(!is_array($arr) || count($arr) <= 0) {
            json_response(0, "数组数据异常！");
        }
        $xml = "<xml>";
        foreach ($arr as $key=>$val)
        {
            if (is_numeric($val)) {
                $xml.="<".$key.">".$val."</".$key.">";
            }else{
                $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
            }
        }
        $xml .= "</xml>";
        return $xml;
    }


    /**
     * Curl操作
     * @param string $type 请求类型 'POST' 或 'GET' 大小写都可以
     * @param string $url 请求地址 url
     * @param array $data 数组 cookie 请求cookie data post请求数据
     * @param bool $headerFile 返回头信息 如果页面做了跳转 则可以从返回头信息获得跳转地址，应用场景不多
     * @return bool|mixed
     */
    private function curl($type, $url, $data=[], $headerFile=false) {
        $type = strtoupper($type);
        $type_list = ['POST', 'GET', 'PUT'];
        if(!in_array($type, $type_list)) $type = 'POST';
        $ch = curl_init();
        // 请求类型
        if($type == 'POST') {
            curl_setopt($ch, CURLOPT_POST, 1);
        }else if($type == 'PUT') {
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST,"PUT"); //设置请求方式
        }
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
        curl_setopt($ch, CURLOPT_ENCODING, ''); // 这个是解释gzip内容, 解决获取结果乱码 gzip,deflate
        // 是否存在请求字段信息
        if(!empty($data['data'])) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data['data']);
        }
        // 是否存在cookie
        if(!empty($data['cookie'])) {
            curl_setopt($ch, CURLOPT_COOKIE, $data['cookie']);
        }
        // 请求头
        if(!empty($data['header'])) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $data['header']);
        }

        // 证书
        if(!empty($data['ssl_cert'])) {
            curl_setopt($ch,CURLOPT_SSLCERT, $data['ssl_cert']);
        }
        if(!empty($data['ssl_key'])) {
            curl_setopt($ch,CURLOPT_SSLKEY, $data['ssl_key']);
        }

        // 返回ResponseHeader
        if($headerFile) {
            curl_setopt($ch, CURLOPT_HEADER, 1);
        }
        // 设置请求超时时间
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        // 发送请求
        $result = curl_exec($ch);
        if (curl_errno($ch)) return false;
        curl_close($ch);
        return $result;
    }
}